﻿using Core.Audit;
using Core.Domain.Entities;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Persistence;
using Finbuckle.MultiTenant.Abstractions;
using Infrastructure.Tenant;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace Infrastructure.Persistence;

public sealed class IdentityDbContext : BoilerplateDbContext, IIdentityDbContext
{
    public const string SchemaName = "identity";
    private readonly IOptions<DatabaseOptions> _settings;

    public IdentityDbContext(
        IMultiTenantContextAccessor<BoilerplateTenantInfo> multiTenantContextAccessor,
        DbContextOptions<IdentityDbContext> options,
        IPublisher publisher,
        IOptions<DatabaseOptions> settings)
        : base(multiTenantContextAccessor, options, publisher, settings)
    {
        _settings = settings;
    }

    public DbSet<Permission> Permissions => Set<Permission>();
    public DbSet<Role> Roles => Set<Role>();
    public DbSet<RolePermission> RolePermissions => Set<RolePermission>();
    public DbSet<User> Users => Set<User>();
    public DbSet<UserRole> UserRoles => Set<UserRole>();
    public DbSet<AuditTrail> AuditTrails => Set<AuditTrail>();
    public DbSet<Organization> Organizations => Set<Organization>();
    public DbSet<UserOrganization> UserOrganizations => Set<UserOrganization>();
    public DbSet<TenantPermission> TenantPermissions => Set<TenantPermission>();
    public DbSet<TenantPermissionHistory> TenantPermissionHistories => Set<TenantPermissionHistory>();
    public DbSet<UserProfile> UserProfiles => Set<UserProfile>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        ArgumentNullException.ThrowIfNull(modelBuilder);
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(IdentityDbContext).Assembly);
        modelBuilder.HasDefaultSchema(SchemaName);
        modelBuilder.ConfigureDateTimeForPostgreSQL(_settings.Value);
    }
}
